package com.itheima.controller;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class FileUploadController {

    @RequestMapping("/fileupload.do")
    public String fileupload(MultipartFile[] files, HttpServletRequest request) throws IOException {
        for (MultipartFile file : files) {
            if (!file.isEmpty()){
                //获取到上传文件的具体名称
                String originalFilename = file.getOriginalFilename();
                //进行截取
                String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
                //进行判断
                if (substring.equalsIgnoreCase(".png") || substring.equalsIgnoreCase(".jsp")){
                    //随机创建名称
                    String s = UUID.randomUUID().toString();
                    //获取到组合名称的真实路径
                    String realPath = request.getServletContext().getRealPath("/upload/" + s + substring);
                    //进行数据的上传
                    file.transferTo(new File(realPath));
                }else {
                    return "选择的图片类型出错";
                }
            }
        }
        return "uploadsuccess.html";
    }
}
